/**
 * 
 * Copyright (C) 2015 by Elcom Software Company
 *
 * @id: FBCallGrapAPI.java, May 8, 2015
 *
 */
package com.nip.fblike.grapapi;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author ThangNM<thangnm@elcom.com.vn>
 *
 * @version v
 */
public class FBCallGrapAPI {
    
    private final ExecutorService service = Executors.newCachedThreadPool();
    private static final FBCallGrapAPI instance = new FBCallGrapAPI();
    
    public static final FBCallGrapAPI instance()
    {
        return instance;
    }
    
    /**
     * @param httpClient
     */
    public FBCallGrapAPI() {
        super();
    }
    
    
    public void call(GraphAPIBase api)
    {
        service.submit(new ApiProcess(api));
    }
    
    
    class ApiProcess implements Runnable
    {

        private final GraphAPIBase api;
        
        
        /**
         * @param api
         */
        public ApiProcess(GraphAPIBase api) {
            super();
            this.api = api;
        }



        /* (non-Javadoc)
         * @see java.lang.Runnable#run()
         */
        @Override
        public void run() {

            String jsonStr = null;
            try
            {
                jsonStr = readUrl(api.getUrl());
                
            }catch(Exception e)
            {
                e.printStackTrace();
            }finally
            {
                api.parser(jsonStr);
            }
        }
        
        private String readUrl(String urlString) throws Exception {
            BufferedReader reader = null;
            try {
                URL url = new URL(urlString);
                reader = new BufferedReader(new InputStreamReader(
                        url.openStream()));
                StringBuffer buffer = new StringBuffer();
                int read;
                char[] chars = new char[1024];
                while ((read = reader.read(chars)) != -1)
                    buffer.append(chars, 0, read); 

                return buffer.toString();
            } finally {
                if (reader != null)
                    reader.close();
            }
        }
        
    }
}
